package com.example.hello.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.hello.entity.DeptDO;
import com.example.hello.mapper.DeptMapper;
import com.example.hello.model.PageRequest;
import com.example.hello.model.PageResult;
import com.example.hello.service.DeptService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.example.hello.service.RedisService;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RedisServiceImpl redisServiceImpl;

    private static final String CACHE_KEY = "dept";

    @Override
    public List<DeptDO> getAllDepts() {
        List<DeptDO> depts = deptMapper.selectAll();
        // 将所有部门信息缓存到Redis
        depts.forEach(dept -> {
            redisServiceImpl.hset(CACHE_KEY, dept.getId().toString(), dept);
        });
        return depts;
    }

    // 分页查询部门
    @Override
    public PageResult<DeptDO> getDeptPage(PageRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        Page<DeptDO> page = (Page<DeptDO>) deptMapper.selectByName(request.getName());

        PageResult<DeptDO> result = new PageResult<>();
        result.setList(page.getResult());
        result.setTotal(page.getTotal());
        result.setPages(page.getPages());
        result.setPageNum(page.getPageNum());
        result.setPageSize(page.getPageSize());
        return result;
    }

    @Override
    public DeptDO getDeptById(Integer id) {
        // 先从Redis获取
        DeptDO dept = (DeptDO) redisServiceImpl.hget(CACHE_KEY, id.toString());
        if (dept == null) {
            // Redis未命中,从数据库获取并缓存
            dept = deptMapper.selectById(id);
            if (dept != null) {
                redisServiceImpl.hset(CACHE_KEY, id.toString(), dept);
            }
        }
        return dept;
    }

    @Override
    @Transactional
    public void createDept(DeptDO dept) {
        // 检查部门名称是否已存在
        if (deptMapper.checkNameExists(dept.getName()) > 0) {
            throw new RuntimeException("部门名称已存在");
        }
        deptMapper.insert(dept);
        // 新增后缓存
        redisServiceImpl.hset(CACHE_KEY, dept.getId().toString(), dept);
    }

    @Override
    @Transactional
    public void updateDept(Integer id) {
        DeptDO dept = new DeptDO();
        dept.setId(id);
        deptMapper.update(dept);
        // 更新后删除缓存
        redisServiceImpl.hdel(CACHE_KEY, id.toString());
    }

    @Override
    @Transactional
    public void deleteDept(Integer id) {
        deptMapper.deleteById(id);
        // 删除后删除缓存
        redisServiceImpl.hdel(CACHE_KEY, id.toString());
    }
}